var libraries = MojoLoader.require({ name: "foundations", version: "1.0" });
var StringUtils = libraries["foundations"].StringUtils;
var Future      = libraries["foundations"].Control.Future;

var configObject = null;
var username = null;

function MainAssistant() {};

MainAssistant.prototype.setup = function() {
    this.debugContainer = this.controller.get("debugOutput");
    this.testDiv = this.controller.get("testDiv");
    this.logOutputNum = 0;
    
// Setup Widgets// User id	

// Password
	this.passwordModel = { value: "" };
	this.controller.setupWidget("login_txtPassword",
			  this.attributes = {
			      hintText: "Type Password",
				  enterSubmits: true
			  },
			  this.passwordModel
			); 

// Set up Buttons

// callLogin button	
	this.controller.setupWidget("callLogin", { type: Mojo.Widget.activityButton },
		    {
			label : "Login",
			buttonClass : "buttonfloat affirmative",
		    }
		  ); 
	Mojo.Event.listen(this.controller.get("callLogin"), Mojo.Event.tap, 
				    this.callLogin.bind(this)
				  ); 
				  
// callRequestList button	
	this.controller.setupWidget("getRequestList", { type: Mojo.Widget.activityButton },
		    {
			label : "Get Request List",
			buttonClass : "buttonfloat affirmative",
		    }
		  ); 
	Mojo.Event.listen(this.controller.get("getRequestList"), Mojo.Event.tap, 
				    this.callGetRequestList.bind(this)
				  ); 
				  
// callRequestDetails button	
	this.controller.setupWidget("getRequestDetails", { type: Mojo.Widget.activityButton },
		    {
			label : "Get Request Details",
			buttonClass : "buttonfloat affirmative",
		    }
		  ); 
	Mojo.Event.listen(this.controller.get("getRequestDetails"), Mojo.Event.tap, 
				    this.callGetRequestDetails.bind(this)
				  ); 
};

MainAssistant.prototype.callLogin = function(event) {

    var f = new Future();
    //Mojo.Log.info("configObject before trans " + JSON.stringify(configObject));

    var configObj = configObject;
    
	//test for HPED
	//callTransService(configObj, 'login', {"credential_0":"qing-yi.wang@hp.com","credential_1":this.passwordModel.value}, f);
    //test for ITRTT
    //callTransService(configObj, 'login', {"actionType": "logon","username":"qing-yi.wang@hp.com","password":this.passwordModel.value,"submit": "Log on"}, f);
    //test for SRPA 
    //callTransService(configObj, 'login', {"__requestHeaders": {Authorization: "Basic " + encode64("qing-yi.wang@hp.com:"+this.passwordModel.value)}}, f);
    //test for ATHP 
    callTransService(configObj, 'login', {"USER":"huixin.ma@hp.com","PASSWORD": this.passwordModel.value}, f);
    //test for INFRASEC
    //callTransService(configObj, 'login', {"username":"qing-yi.wang@hp.com","passowrd": this.passwordModel.value, "submit":"Login"}, f);
    
    f.then( function(future) {
        this.logMsg( "code : " + future.result.code +", Service Return: " +JSON.stringify(future.result.reply));     
        Mojo.Log.info(" future result ", JSON.stringify(future.result));
        this.controller.get("callLogin").mojo.deactivate();
		username = f.result.reply[0].username;
    }.bind(this));
};

MainAssistant.prototype.callReworkTimesheet = function(event) {
    var f = new Future();
    //Mojo.Log.info("configObject before trans " + JSON.stringify(configObject));

    var configObj = configObject;
    
    //callTransService(configObj, 'getRequestList', {}, f);
    callTransService(configObj, 'getPPMTimesheetbyID', {"timesheetId":'2522436'}, f);
	//callTransService(configObj, 'savePPMNextTimesheet', {}, f);
	//callTransService(configObj, 'getPPMTimesheetbyID', {"timesheetId":'2517793'}, f);
	

	
	//callTransServiceR2F(configObj, 'savePPMNextTimesheet', {}, this.controller,f);
	//callTransService(configObj, 'getPPMTimesheetbyID', {"timesheetId":'2517793'}, f);
	//callTransServiceR2F(configObj, 'getPPMTimesheetbyID', {"timesheetId": "2517793"}, this.controller,f);
    //callTransService(configObj, 'getITTopStories', {}, f);
    
    f.then( function(future) {
		var i = 0;
		var values = future.result.reply;
		var r_contextId;
		var r_obj_num;
		var r_timesheetId;
		var r_desc;
		
		while(i < values.length ) {
			if (values[i].contextId ) {
				r_contextId = values[i].contextId;
				r_obj_num = values[i].OBJECT_VERSION_NUMBER;
				r_desc = values[i].description;
			}
			if (values[i].timesheet_id) {
				r_timesheetId = values[i].timesheet_id;
			}
			i++;
		}
		

	    var params = {
		             "contextId":r_contextId,
					 "OBJECT_VERSION_NUMBER":r_obj_num,
					 "LOAD_PAGE_URL":escape("/itg/tm/SearchTimeSheets.do?NAV_PATH_LINK=Y&amp;title=Search+Time+Sheets&amp;IS_WINDOID=N&amp;IS_PM_PAGE=true&amp;NAV_SEQ=0"),
					 //"TASK_466540_30098_3":"14.00",
					 "timesheetId": r_timesheetId,
					 "description": r_desc
                     };
					 
		//generate the parameters for each day
		//to reach the 3rd newblock
		j = 0; i = 0;
		while( j < values.length ) {
			if( values[j].block ) { i++ };
			if (i == 3) { j++; break; };
			j++;
		}
		
		//collect the task id
		i = 0;
		while( j < values.length ) {
			if (values[j].Status) {
				params[values[j].TaskID] = "Y";
				params["<<<<tsLineIndex>>>>"+i] = i;
				i++;
			}
			j++;
		}
		
		/*while( j < values.length ) {
		    if( values[j].block ) {break;};
			if( values[j].task_id_3.length > 0 ) {
				for(k = 0; k < 7; k++) {
					params[ (values[j].task_id_1 + "_"+ values[j].task_id_2 +"_"+ values[j].task_id_3 +"_"+k) ] = "3.00";
					logInfo(values[j].task_id_1 + "_"+ values[j].task_id_2 +"_"+ values[j].task_id_3 +"_"+k);
				}
			};
			j++;
		}*/
	
		callTransService(configObj, 'reworkPPMTimesheet', params, f);		 
	    //callTransServiceR2F(configObj, 'savePPMTimesheet', params, this.controller,f);
		//callTransService(configObj, 'savePPMTimesheet', params, f);
		//callTransService(configObj, 'releasePPMTimesheet', params, f);
		//callTransServiceR2F(configObj, 'releasePPMTimesheet', params,this.controller, f);
		
		f.then( function(future) {
		  this.logMsg( "code : " + future.result.code +", Service Return: " +JSON.stringify(future.result.reply)); 
		}.bind(this));
		
        this.logMsg( "code : " + future.result.code +", Service Return: " +JSON.stringify(future.result.reply));    
        Mojo.Log.info(" future result ", JSON.stringify(future.result));
        this.controller.get("getRequestList").mojo.deactivate();
    }.bind(this));

};

MainAssistant.prototype.callReleaseTimesheet = function(event) {
    var f = new Future();
    //Mojo.Log.info("configObject before trans " + JSON.stringify(configObject));

    var configObj = configObject;
    

    callTransService(configObj, 'getPPMTimesheetbyID', {"timesheetId":'2522436'}, f);

    
    f.then( function(future) {
		var i = 0;
		var values = future.result.reply;
		var r_contextId;
		var r_obj_num;
		var r_timesheetId;
		var r_desc;
		
		//generate params
		while(i < values.length ) {
			if (values[i].contextId ) {
				r_contextId = values[i].contextId;
				r_obj_num = values[i].OBJECT_VERSION_NUMBER;
				r_desc = values[i].description;
			}
			if (values[i].timesheet_id) {
				r_timesheetId = values[i].timesheet_id;
			}
			i++;
		}
	    var params = {
		             "contextId":r_contextId,
					 "OBJECT_VERSION_NUMBER":r_obj_num,
					 "LOAD_PAGE_URL":"/itg/tm/SearchTimeSheets.do?NAV_PATH_LINK=Y&amp;title=Search+Time+Sheets&amp;IS_WINDOID=N&amp;IS_PM_PAGE=true&amp;NAV_SEQ=0",
					 //"TASK_466540_30098_3":"14.00",
					 "timesheetId": r_timesheetId,
					 "description": r_desc
                     };
					 
		//generate the parameters for each day
		//to reach the 1st newblock, j is the index
		j = 0; i = 0;
		while( j < values.length ) {
			if( values[j].block ) { i++ };
			if (i == 1) { j++; break; };
			j++;
		}
		
		//collect the task id
		i = 0;
		while( j < values.length ) {
		    if( values[j].block ) {break;};
			if( values[j].task_id_3.length > 0 ) {
				for(k = 0; k < 7; k++) {
					params[ (values[j].task_id_1 + "_"+ values[j].task_id_2 +"_"+ values[j].task_id_3 +"_"+k) ] = "2.00";
					logInfo(values[j].task_id_1 + "_"+ values[j].task_id_2 +"_"+ values[j].task_id_3 +"_"+k);
				}
			};
			j++;
		}
	
		callTransService(configObj, 'releasePPMTimesheet', params, f);
		
		f.then( function(future) {
		  this.logMsg( "code : " + future.result.code +", Service Return: " +JSON.stringify(future.result.reply)); 
		}.bind(this));
		
        this.logMsg( "code : " + future.result.code +", Service Return: " +JSON.stringify(future.result.reply));    
        Mojo.Log.info(" future result ", JSON.stringify(future.result));
        this.controller.get("getRequestList").mojo.deactivate();
    }.bind(this));
};

MainAssistant.prototype.callGetRequestList = function(event) {
  this.callReworkTimesheet(event);
    
};

MainAssistant.prototype.callCreateTimesheet = function(event) {
    var f = new Future();
    //Mojo.Log.info("configObject before trans " + JSON.stringify(configObject));

    var configObj = configObject;
	
	var params = {
					    "periodId":"30246",
						"resource":username,
						"resourceHV":"",
						"description":"created by mobile for test",
						"includePrevWorkItems":"on",
						"lastTimeSheet":"2513245",
						"actionCreate":"Y",
						"copyTimeSheet":"false",
						"sourceTimeSheetId":"2513245"
	             };
				 
	callTransService(configObj, 'createTimesheetbyCopy',  params,  f);
	
	
	
	//callTransService(configObj, 'reworkPPMTimesheet', {}, f);
    //callTransService(configObj, 'getPPMTimesheetByResource', {"criteria(tsResource)":username}, f);
    //callTransServiceR2F(configObj, 'getRequestDetailsA', {"requestID":"RqAc_9849"}, this.controller,f);
    //callTransService(configObj, 'performPPMTimesheetApproval', {"tsSearchSelected%282414132_2%29":"on"}, f);
    
    f.then( function(future) {
        this.logMsg( "code : " + future.result.code +", Service Return: " +JSON.stringify(future.result.reply));     
        Mojo.Log.info(" future result ", JSON.stringify(future.result));
        this.controller.get("getRequestDetails").mojo.deactivate();
    }.bind(this));

}

MainAssistant.prototype.callGetPeriod = function(event) {
    var f = new Future();
    //Mojo.Log.info("configObject before trans " + JSON.stringify(configObject));

    var configObj = configObject;
	
	callTransService(configObj, 'getPPMTimePeriod', {}, f);
    
    f.then( function(future) {
        this.logMsg( "code : " + future.result.code +", Service Return: " +JSON.stringify(future.result.reply));     
        Mojo.Log.info(" future result ", JSON.stringify(future.result));
        this.controller.get("getRequestDetails").mojo.deactivate();
    }.bind(this));

};

MainAssistant.prototype.callGetTimesheet = function(event) {
    var f = new Future();
    //Mojo.Log.info("configObject before trans " + JSON.stringify(configObject));

    var configObj = configObject;
	
	
	//callTransServiceR2F(configObj, 'getPPMTimesheetbyID', {"timesheetId":'2522329'},this.controller, f);
	callTransService(configObj, 'getPPMTimesheetbyID', {"timesheetId":'2522329'}, f);

    
    f.then( function(future) {
        this.logMsg( "code : " + future.result.code +", Service Return: " +JSON.stringify(future.result.reply));     
        Mojo.Log.info(" future result ", JSON.stringify(future.result));
        this.controller.get("getRequestDetails").mojo.deactivate();
    }.bind(this));

};

MainAssistant.prototype.callGetRequestDetails = function(event) {

	//this.callGetPeriod(event);
	//this.callCreateTimesheet(event);
	//this.callGetTimesheet(event);
};


MainAssistant.prototype.activate = function(event) {
    var that = this;
    this.logMsg("Setup");
    
    // Call the Hello World service using standard Palm serviceRequest
    //com.bbhome.testservice.service
    //com.hpit.cdc.pagetrans.service
   this.logMsg("beging load configuration");
   
   var f = new Future();
   
   getConfiguration('PPM_engine_config.json', this.controller, f);
   //getConfiguration('ITRTT_engine_config.json', this.controller, f);
   //getConfiguration('HPED_engine_config.json', this.controller, f);
   //getConfiguration('SRPA_engine_config.json', this.controller, f);
   //getConfiguration('athp_engine_config.json', this.controller, f);
   //getConfiguration('INFRASEC_engine_config.json', this.controller, f);
   //getConfiguration('News_engine_config.json', this.controller, f);
   
   f.then( function(future) {
     this.loadConfigSuc(future.result);
   }.bind(this));

};

MainAssistant.prototype.loadConfigSuc = function(configObj) {
   configObject = configObj.reply;
   Mojo.Log.info("in success function configObj " + JSON.stringify(configObj));
   this.logMsg("successfully load configuration instance " + configObject.instance_name);
};

MainAssistant.prototype.loadConfigFail = function() {
   Mojo.Log.info("configObj failed");
   this.logMsg("configObj failed");
};


MainAssistant.prototype.serviceSuccess = function(successData){
    this.logMsg("Success Data: " + JSON.stringify(successData) + "  ");
    
    Mojo.Log.info("Success Data: " + JSON.stringify(successData) + "  ");
    
    configObj = successData.reply;
    
//    this.controller.serviceRequest("palm://com.hpit.cdc.pagetrans.service", {
//        method: "process",
//        parameters: {'servicename': 'testHeader'},
//        onSuccess:this.serviceSuccess2.bind(this),
//        onFailure:this.serviceFailure.bind(this)
//    });
};
MainAssistant.prototype.serviceFailure = function(failData){
    this.logMsg("Fail Data:" + JSON.stringify(failData));
};

MainAssistant.prototype.deactivate = function(event) {};

MainAssistant.prototype.cleanup = function(event) {};

MainAssistant.prototype.logMsg = function(logText) {
    this.debugContainer.innerHTML = "" + (this.logOutputNum++) + ": " + StringUtils.escapeHTML(logText) + "<br/>" + this.debugContainer.innerHTML;
    //this.debugContainer.innerHTML = (this.logOutputNum++) + ": " + logText + "" + this.debugContainer.innerHTML;            
};    

MainAssistant.prototype.serviceSuccess2 = function(successData){ 
  this.logMsg("Success2 Data: " + JSON.stringify(successData) + "  ");
  Mojo.Log.info("Success2 Data: " + JSON.stringify(successData) + "  ");
}
